package calvin.controller.cron;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.datanucleus.util.StringUtils;
import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import org.slim3.datastore.Datastore;

import calvin.datastore.meta.Rate5mMeta;
import calvin.datastore.model.Rate1d;
import calvin.datastore.model.Rate5m;
import calvin.utils.RateHelper;

import com.google.appengine.api.datastore.Key;

public class Generate1dTickController extends Controller {

    @Override
    public Navigation run() throws Exception {
        
        Date end = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHH");
        
        if(StringUtils.isEmpty(asString("hour"))) {
            Date c = new Date(System.currentTimeMillis());
            String s = sdf.format(c);
            end = sdf.parse(s);
        } else {
            end = sdf.parse(asString("hour"));
        }
        
        Date start = new Date(end.getTime() - 24 * 60 * 60 * 1000);// 1day
        Iterator<String> it = RateHelper.WATCH_SET.iterator();
        while(it.hasNext()) {
            String cp = it.next();
            Rate5mMeta e = Rate5mMeta.get();
            List<Rate5m> list = Datastore.query(e)
                .filter(e.cp.equal(cp))
                .filter(e.t.greaterThanOrEqual(start))
                .filter(e.t.lessThan(end))
                .sort(e.t.asc)
                .asList();
            if(list.size() == 0) {
                continue;
            }
            Double l = null;
            Double h = null;
            Double o = null;
            Double c = null;
            for(int i = 0; i < list.size(); i++) {
                Rate5m r = list.get(i);
                Double high = r.getH();
                Double low = r.getL();
                if(i == 0) {
                    o = r.getO();
                } else if(i == list.size() - 1) {
                    c = r.getC();
                }
                if(l == null || l.doubleValue() > low.doubleValue()) {
                    l = low;
                }
                if(h == null || h.doubleValue() < high.doubleValue()) {
                    h = high;
                }
            }
            Rate1d entity = new Rate1d();
            Key key = Datastore.createKey(Rate1d.class, cp + sdf.format(start));
            entity.setKey(key);
            entity.setCp(cp);
            entity.setH(h);
            entity.setL(l);
            entity.setC(c);
            entity.setO(o);
            entity.setT(start);
            Datastore.put(entity);
        }

        return null;
    }
}
